/*
	---------------------------------------------
	-	Content Handling Scripts
	-	/core.app.js
	-	Runs content changes
	---------------------------------------------
	-	Author(s):	James Haley
		-			james.haley@wapisasa.com
		-			24/09/2013 13:25:10
	---------------------------------------------
*/

	//	++ App Initialisation
	//----------------------------------------------
	//	App/Page specific actions
	
		(site.app = {
			setup:function(){
				// Initiate
				site.app.interact.setup();
			},
			//	++ Get page scroll height
			//----------------------------------------------
			getScrollHeights:function(){
				var oBody=document.body,oHTML=document.documentElement;
				return Math.max(oBody.scrollHeight,oBody.offsetHeight,oHTML.clientHeight,oHTML.scrollHeight,oHTML.offsetHeight);
			},
			//	++ Get page scroll position from the bottom
			//----------------------------------------------
			currentScrollBottom:function(){
				return (site.app.getScrollHeights()-document.viewport.getHeight())-document.viewport.getScrollOffsets().top;
			}
		});

	//	++ Interactions
	//----------------------------------------------
	//	Handle interactions like slideshows
	
		(site.app.interact = {
			setup:function(){
				// Run slide shows
				var oSlideShow = $$('[data-interact="slideshow"]');
				oSlideShow.each(site.app.interact.createSlideShow.setup);				
			},
			createSlideShow:{
				timer:'',
				setup:function(o){
					// Check how many slides and set width
					var oSlides = o.select('.slide'), nTotalSlides = oSlides.length, nTotalWidth = 0, nOneSlideWidth = 0;
					oSlides.each(
						function(oSlide){
							nTotalWidth+=oSlide.offsetWidth;
							nOneSlideWidth=(nOneSlideWidth===0)?oSlide.offsetWidth:nOneSlideWidth;
						}
					);

					if(oSlides.length>0){
						// Check for handles/triggers
						var oHandles = $$('[data-interact="slide-handles"][data-linked="'+o.identify()+'"]').first().hide(), // Get handle holder, but hide it
							oHandleType=oHandles.readAttribute('data-handle'),
							oHandlePrev = $$('[data-interact="slide-handle-prev"][data-linked="'+o.identify()+'"]').first(),
							oHandleNext = $$('[data-interact="slide-handle-next"][data-linked="'+o.identify()+'"]').first(),
							vPlayMode=o.readAttribute('data-play'),
							vControlsBehavior = o.readAttribute('data-controls-behavior');

						// Slideshow counts dots
						if(oHandleType=='count') {
							var oNewBullet,vClass = 'bullet '+oHandles.readAttribute('data-special-class')||'bullet';
							oSlides.each(
								function(oSlide,nI){
									oNewBullet = new Element('div',{className:vClass}).writeAttribute({'data-handle-index':nI}).update('<a href="javascript:;">'+(nI+1)+'</a>');
									oNewBullet.down('a').observe('click',function(){
										var nNewTarget=(nOneSlideWidth*nI);
										o.writeAttribute({'data-interact-target':'-'+nNewTarget+'px'});
										o.fire('interact:updated');
										o.fire('interact:autoplay:restart');
									});
									oHandles.appendChild(oNewBullet);
								}
							);

							// Fade in the handles
							(oSlides.length>1)?oHandles.appear({duration:1,transition:site.app.transition}):null;

							// Check for special layout and set
							var vSpecial = oHandles.readAttribute('data-special');
							if(vSpecial=='centered-large'){
								var nWidth = (44*oSlides.length);
								oHandles.setStyle({'width':nWidth+'px'});
							}
						}

						// Next and Previous slide functions
						var oAutoPlayPoints = oHandles.select('a'),
							oNextSlide = function(){
								var nNextSlide = (parseInt(o.readAttribute('data-slide-position'))+1);
								(nNextSlide==oAutoPlayPoints.length)?nNextSlide=0:null;

								o.writeAttribute({'data-interact-target':'-'+($(oAutoPlayPoints[nNextSlide]).up('div.bullet').readAttribute('data-handle-index')*nOneSlideWidth)+'px'});
								o.fire('interact:updated');
							},
							oPrevSlide = function(){
								var nPrevSlide = (parseInt(o.readAttribute('data-slide-position'))-1);
								(nPrevSlide<0)?nPrevSlide=(oAutoPlayPoints.length-1):null;

								o.writeAttribute({'data-interact-target':'-'+($(oAutoPlayPoints[nPrevSlide]).up('div.bullet').readAttribute('data-handle-index')*nOneSlideWidth)+'px'});
								o.fire('interact:updated');
							}

						// Broadcast next and previous
						o.nextSlide = oNextSlide;
						o.prevSlide = oPrevSlide;

						// Create next and previous links if required
						if(!!oHandlePrev) {
							oHandlePrev.hide().observe('click',function(){
								oPrevSlide();
							});

							// Show on load or mouseover
							if(vControlsBehavior=='show'){
								oHandlePrev.show();
							} else {
								o.observe('mouseenter',function(){oHandlePrev.show()}).observe('mouseleave',function(){oHandlePrev.hide()});
								oHandlePrev.observe('mouseenter',function(){oHandlePrev.show();oHandleNext.show();}).observe('mouseleave',function(){oHandlePrev.hide();oHandleNext.hide();});
							}
						}
						if(!!oHandleNext) {
							oHandleNext.hide().observe('click',function(){
								oNextSlide();
							});

							// Show on load or mouseover
							if(vControlsBehavior=='show'){
								oHandleNext.show();
							} else {
								o.observe('mouseenter',function(){oHandleNext.show()}).observe('mouseleave',function(){oHandleNext.hide()});
								oHandleNext.observe('mouseenter',function(){oHandleNext.show();oHandlePrev.show();}).observe('mouseleave',function(){oHandleNext.hide();oHandlePrev.hide();});
							}
						}


						// Play mode (auto, means a timed playlist, otherwise is manual)
						if(vPlayMode==='auto'){
							var bPaused = false;

							o.observe('interact:autoplay:start',function(oEvent){
								// Old timer delete in case it exists
								o.fire('interact:autoplay:stop');

								// Go go go
								var oTimer = new PeriodicalExecuter(function(oTimer) {
									oNextSlide();
								}, 7);

								// Save timer onto slideshow
								site.app.interact.createSlideShow.timer=oTimer;
							});
							o.observe('interact:autoplay:restart',function(oEvent){
								// Stop timer
								var oTimer = site.app.interact.createSlideShow.timer||'';
								(oTimer!=='')?oTimer.stop():null;
								site.app.interact.createSlideShow.timer='';

								// Allow mouse interactions
								bPaused = false;

								// Restart timer
								o.fire('interact:autoplay:start');
							});
							o.observe('interact:autoplay:stop',function(oEvent){
								// Stop timer
								var oTimer = site.app.interact.createSlideShow.timer||'';
								(oTimer!=='')?oTimer.stop():null;
								site.app.interact.createSlideShow.timer='';
							});
							o.observe('interact:autoplay:pause',function(oEvent){
								// Stop timer
								o.fire('interact:autoplay:stop');

								bPaused = true;
							});
							// Start timer
							o.fire('interact:autoplay:start');

							// Handle mouseovers
							o.observe('mouseenter',function(){
								o.fire('interact:autoplay:stop');
							});
							o.observe('mouseleave',function(){
								(!bPaused)?o.fire('interact:autoplay:start'):null;
							});
						}

						// Handle touch events (check Hammer.js is present)
						if(window.Hammer!==undefined){
							Hammer(o).on("swiperight", function() {
								oPrevSlide();
							});
							Hammer(o).on("swipeleft", function() {
								oNextSlide();
							});
						}

						// Set overall width of slider
						o.setStyle({'width':nTotalWidth+'px'});
						
						// Setup watcher for handles
						o.observe('interact:updated',function(oEvent){
							var nCurrentTarget = parseInt(o.readAttribute('data-interact-target')),
								nCurrentSlide = (Math.abs(nCurrentTarget)/nOneSlideWidth);

							// Set slide number
							o.writeAttribute({'data-slide-position':nCurrentSlide});
							
							if(oHandleType=='count'){
								oHandles.select('.bullet').each(function(oH){
									(oH.readAttribute('data-handle-index')==nCurrentSlide)?oH.addClassName('on'):oH.removeClassName('on');
								});
							}
							
							// Update Images
							var oMoveEffect = new Effect.Move(o, { x: nCurrentTarget, mode: 'absolute', fps:150, duration:1, transition:site.app.transition, queue:{position:'end',scope:'interact_'+o.identify()} });
						});
						
						// Initial setup
						o.fire('interact:updated');
					}
				}
			}
		});
		
	//	++ Queue up for initialisation
	//----------------------------------------------
	site.setup._initial.push(site.app.setup);